#include <stdio.h>
#include <string.h>
#include <ip2c.h>

int main(int argc, char *argv[])
{
	struct ip2c_db *db;
	FILE *f;
	char *lineptr = NULL, *ip_c = NULL, *ip_s = NULL, *ip_e = NULL;
	int n = 0, bytes_read = 0;
	unsigned long ip_count = 0;

	if(argc != 2)
	{
		printf("Usage: %s <file_name>\n", argv[0]);
		return 1;
	}

	if(f = fopen(argv[1], "r"))
	{
		db = (struct ip2c_db *)ip2c_db_init();

		printf("Reading `%s`\n", argv[1]);
		while(!feof(f))
		{
			lineptr = NULL;
			bytes_read = getline(&lineptr, &n, f);
			if((bytes_read == -1) || (ip_c = strtok(lineptr, ",")) == NULL)
			{
				continue;
			}
			ip_s = strtok(NULL, ",");
			ip_e = strtok(NULL, "\n");
			ip2c_db_insert(db, ip_c, strtoul(ip_s, NULL, 0), strtoul(ip_e, NULL, 0));
//			printf("%lu,%lu\n", strtoul(ip_s, NULL, 0), strtoul(ip_e, NULL, 0));
//			_flushlbf();
		}
		fclose(f);

		if(ip2c_db_save(db, "ip2c.db") == 0)
		{
			printf("Wrote %d records\n", db->rec_count);
		}
		ip2c_db_version(db);
		ip2c_db_free(db);
	} else {
		fprintf(stderr, "Error: cannot open file `%s`\n", argv[1]);
		return 1;
	}

	return 0;
}
